<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="绘本标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入绘本标题" />
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input v-model="formData.author" placeholder="请输入作者" />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="formData.categoryId" placeholder="请选择分类" class="w-full">
          <el-option
            v-for="category in categoryList"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="封面图片" prop="coverUrl">
        <UploadImg v-model="formData.coverUrl" :limit="1" />
      </el-form-item>
      <el-form-item label="页数" prop="pageCount">
        <el-input-number
          v-model="formData.pageCount"
          :min="1"
          :max="999"
          placeholder="请输入页数"
          class="w-full"
        />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="4"
          placeholder="请输入绘本描述"
        />
      </el-form-item>
      <el-form-item label="语言" prop="language">
        <el-select v-model="formData.language" placeholder="请选择语言" class="w-full">
          <el-option label="中文" value="zh" />
          <el-option label="英文" value="en" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { createBook, updateBook, getBook, getBookCategories, type BookVO } from '@/api/miniprogram/book'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import UploadImg from '@/components/UploadFile/src/UploadImg.vue'
import Dialog from '@/components/Dialog/src/Dialog.vue'

/** 绘本表单 */
defineOptions({ name: 'BookForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  title: '',
  author: '',
  categoryId: undefined,
  coverUrl: '',
  description: '',
  pageCount: 1,
  language: 'zh',
  status: 1
})
const formRules = reactive({
  title: [{ required: true, message: '绘本标题不能为空', trigger: 'blur' }],
  author: [{ required: true, message: '作者不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '分类不能为空', trigger: 'change' }],
  coverUrl: [{ required: true, message: '封面图片不能为空', trigger: 'blur' }],
  pageCount: [{ required: true, message: '页数不能为空', trigger: 'blur' }],
  language: [{ required: true, message: '语言不能为空', trigger: 'change' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const categoryList = ref<any[]>([]) // 分类列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '添加绘本' : '修改绘本'
  formType.value = type
  resetForm()
  
  // 获取分类列表
  await getCategoryList()
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await getBook(id)
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BookVO
    if (formType.value === 'create') {
      await createBook(data)
      message.success(t('common.createSuccess'))
    } else {
      await updateBook(data.id!, data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: '',
    author: '',
    categoryId: undefined,
    coverUrl: '',
    description: '',
    pageCount: 1,
    language: 'zh',
    status: 1
  }
  formRef.value?.resetFields()
}

/** 获取分类列表 */
const getCategoryList = async () => {
  try {
    const data = await getBookCategories()
    categoryList.value = data
  } catch {}
}

/** 暴露给父组件的方法 */
defineExpose({ open })
</script>